import { Bar } from 'react-chartjs-2'
import './setup' // 确保Chart.js组件被注册
import { commonOptions, colors } from './chartConfig'
import { getPriorityLabel } from '../../utils'

interface PriorityStats {
  priority: string
  total: number
  completed: number
  pending: number
  completionRate: number
}

interface PriorityBarChartProps {
  data: PriorityStats[]
}

export default function PriorityBarChart({ data }: PriorityBarChartProps) {
  if (data.length === 0) {
    return (
      <div className="h-64 flex items-center justify-center text-theme-text-muted">
        <div className="text-center">
          <div className="w-16 h-16 bg-theme-bg-tertiary rounded-full flex items-center justify-center mx-auto mb-3">
            📊
          </div>
          <p>暂无优先级数据</p>
        </div>
      </div>
    )
  }

  // 按优先级排序 (P0 -> P3)
  const sortedData = [...data].sort((a, b) => a.priority.localeCompare(b.priority))

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case 'P0': return colors.error
      case 'P1': return colors.warning
      case 'P2': return colors.primary
      case 'P3': return colors.success
      default: return colors.primary
    }
  }

  const chartData = {
    labels: sortedData.map(item => getPriorityLabel(item.priority)),
    datasets: [
      {
        label: '已完成',
        data: sortedData.map(item => item.completed),
        backgroundColor: sortedData.map(item => getPriorityColor(item.priority).bg),
        borderColor: sortedData.map(item => getPriorityColor(item.priority).border),
        borderWidth: 2,
        borderRadius: 6,
        borderSkipped: false,
        barThickness: 40,
        maxBarThickness: 60
      },
      {
        label: '待完成',
        data: sortedData.map(item => item.pending),
        backgroundColor: sortedData.map(item => 
          getPriorityColor(item.priority).bg.replace('0.8', '0.3')
        ),
        borderColor: sortedData.map(item => getPriorityColor(item.priority).border),
        borderWidth: 2,
        borderRadius: 6,
        borderSkipped: false,
        barThickness: 40,
        maxBarThickness: 60
      }
    ]
  }

  const options = {
    ...commonOptions,
    plugins: {
      ...commonOptions.plugins,
      tooltip: {
        ...commonOptions.plugins?.tooltip,
        callbacks: {
          title: (context: any) => {
            return `${context[0].label} 优先级`
          },
          label: (context: any) => {
            const datasetLabel = context.dataset.label
            const value = context.parsed.y
            const total = sortedData[context.dataIndex].total
            const percentage = total > 0 ? Math.round((value / total) * 100) : 0
            return `${datasetLabel}: ${value} 个 (${percentage}%)`
          },
          afterBody: (context: any) => {
            const index = context[0].dataIndex
            const item = sortedData[index]
            return [`总计: ${item.total} 个任务`, `完成率: ${item.completionRate}%`]
          }
        }
      }
    },
    scales: {
      ...commonOptions.scales,
      x: {
        ...commonOptions.scales?.x,
        stacked: true
      },
      y: {
        ...commonOptions.scales?.y,
        stacked: true,
        beginAtZero: true,
        ticks: {
          ...commonOptions.scales?.y?.ticks,
          stepSize: 1
        }
      }
    },
    animation: {
      duration: 1200,
      easing: 'easeOutBounce' as const
    }
  }

  return (
    <div className="h-64">
      <Bar data={chartData} options={options} />
    </div>
  )
}
